package com.study.ssm.factory;

import com.study.ssm.factory.bean.Customer;
import com.study.ssm.factory.bean.Person;
import com.study.ssm.factory.bean.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.Connection;

/**
 * @author zhoujunlin
 * @date 2023年07月20日 19:19
 * @desc
 */
public class TestApplicationContext01 {

    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/factory/applicationContext01.xml");

    @Test
    public void test01() {

        // 强转
        Person person = (Person) ctx.getBean("person");
//        System.out.println(person);
        // 指定类型
//        person = ctx.getBean("person", Person.class);
//        System.out.println(person);
        // 上下文中只有一个此类型的bean时
        person = ctx.getBean(Person.class);
        System.out.println(person);
    }

    @Test
    public void test02() {
        //获取的是 Spring⼯⼚配置⽂件中所有bean标签的id值 person person1
        String[] beanDefinitionNames = ctx.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println("beanDefinitionName = " +
                    beanDefinitionName);
        }

        //根据类型获得Spring配置⽂件中对应的id值
        String[] beanNamesForType = ctx.getBeanNamesForType(Person.class);
        for (String id : beanNamesForType) {
            System.out.println("id = " + id);
        }

        //⽤于判断是否存在指定id值得bean
        if (ctx.containsBeanDefinition("a")) {
            System.out.println("true = " + true);
        } else {
            System.out.println("false = " + false);
        }

        //⽤于判断是否存在指定id值得bean
        if (ctx.containsBean("person")) {
            System.out.println("true = " + true);
        } else {
            System.out.println("false = " + false);
        }
    }

    @Test
    public void test03() {
        UserService userService = ctx.getBean("userService", UserService.class);
//        userService.register(new User());
        userService.query("zhoujl", "123456");
    }

    @Test
    public void test04() {
        Customer customer = ctx.getBean("customer", Customer.class);
        System.out.println(customer);
    }

    @Test
    public void test05() {
        // 对象每次新建
        // com.mysql.jdbc.JDBC4Connection@23f7d05d
        Connection connection = ctx.getBean("connection", Connection.class);
        System.out.println(connection);
        // com.mysql.jdbc.JDBC4Connection@60704c
        connection = ctx.getBean("connection", Connection.class);
        System.out.println(connection);

        // com.study.ssm.factory.bean.ConnectionFactoryBean@6b19b79
        Object obj = ctx.getBean("&connection");
        System.out.println(obj);
    }

}
